package com.cw.jeeyt.controller.system;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.system.SystemColumnInfoBo;
import com.cw.jeeyt.service.bo.system.SystemModuleInfoBo;
import com.cw.jeeyt.service.bo.system.SystemTableInfoBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.system.SystemColumnInfoService;
import com.cw.jeeyt.service.intf.system.SystemModuleInfoService;
import com.cw.jeeyt.service.intf.system.SystemTableInfoService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 表字段信息控制类
 *
 * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/systemColumnInfo")
public class SystemColumnInfoController extends BaseController {
    @Autowired
    @Lazy
    private SystemColumnInfoService systemColumnInfoService;
    @Autowired
    @Lazy
    private SystemTableInfoService systemTableInfoService;
    @Autowired
    @Lazy
    private SystemModuleInfoService systemModuleInfoService;

    /**
     * 跳转到列表查询页面
     *
     * @param moduleId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query(String tableId, String moduleId) throws Exception {

        ModelAndView mv = new ModelAndView("system/systemColumnInfo_index");
        SystemTableInfoBo systemTableInfoBo = systemTableInfoService.getSystemTableInfoById(tableId);
        mv.addObject("systemTableInfo", systemTableInfoBo);
        mv.addObject("moduleId", moduleId);
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSystemColumnInfo")
    public ResultData listSystemColumnInfo(@RequestBody DataTable dataTable, String tableId) throws Exception {

        SystemColumnInfoBo systemColumnInfoBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SystemColumnInfoBo.class);
        if (systemColumnInfoBo == null) {
            systemColumnInfoBo = new SystemColumnInfoBo();
        }
        systemColumnInfoBo.setTableId(tableId);
        PageInfo<SystemColumnInfoBo> pageInfo = systemColumnInfoService.queryByPage(systemColumnInfoBo,
            dataTable.getStart(), dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView toForm(String id, String tableId, String moduleId, String operation)
    throws Exception {
        ModelAndView mv = new ModelAndView("system/systemColumnInfo_form");
        SystemColumnInfoBo systemColumnInfoBo;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemColumnInfoBo = new SystemColumnInfoBo();
        } else {
            systemColumnInfoBo = systemColumnInfoService.getSystemColumnInfoById(id);
            tableId = systemColumnInfoBo.getTableId();
        }
        SystemTableInfoBo systemTableInfoBo = systemTableInfoService.getSystemTableInfoById(tableId);
        mv.addObject("systemTableInfo", systemTableInfoBo);
        mv.addObject("systemColumnInfo", systemColumnInfoBo);
        mv.addObject("operation", operation);
        mv.addObject("moduleId", moduleId);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据
     *
     * @param systemColumnInfoBo
     * @param operation add新增  edit修改 view查看
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemColumnInfo", method = RequestMethod.POST)
    public JsonResultDto saveSystemColumnInfo(SystemColumnInfoBo systemColumnInfoBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {

            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                //校验字段编码是否重复
                SystemColumnInfoBo check_systemColumnInfoBo = systemColumnInfoService.checkSystemColumnCode(
                    systemColumnInfoBo);
                if (check_systemColumnInfoBo != null) {
                    jsonResultDto.setMsg("表字段编码已经存在!");
                } else {
                    systemColumnInfoService.insertSystemColumnInfo(systemColumnInfoBo);
                    jsonResultDto.setMsg("保存成功");
                    jsonResultDto.setSuccess(true);
                }
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                systemColumnInfoService.updateSystemColumnInfo(systemColumnInfoBo);
                jsonResultDto.setMsg("保存成功");
                jsonResultDto.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
        }
        jsonResultDto.setOperation(operation);
        return jsonResultDto;
    }

    /**
     * 删除表字段信息
     *
     * @param systemColumnInfoBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto deleteSystemColumnInfo(SystemColumnInfoBo systemColumnInfoBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemColumnInfoService.deleteSystemColumnInfo(systemColumnInfoBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 同步数据库字段信息
     *
     * @param moduleId
     * @throws Exception
     */
    @RequestMapping(value = "/to-importColumnInfo")
    public ModelAndView syncSystemDataEntry(String tableId, String moduleId) throws Exception {

        ModelAndView mv = new ModelAndView("system/systemColumnInfo_syncForm");
        SystemModuleInfoBo systemModuleInfo = systemModuleInfoService.getSystemModuleInfoById(moduleId);

        mv.addObject("tableId", tableId);
        mv.addObject("projectId", systemModuleInfo.getProjectId());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 同步数据条目信息到模型字段表中
     *
     * @param tableId
     * @throws Exception
     */
    @RequestMapping(value = "/importDataEntry")
    @ResponseBody
    public JsonResultDto importDataEntry(String tableId, String dataEntryStr, String isPk) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemColumnInfoService.importDataEntry(tableId, dataEntryStr, isPk);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 保存表模型字段页面配置信息
     *
     * @param columnJson 页面配置信息
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveColumnInfoPageConfig", method = RequestMethod.POST)
    public JsonResultDto saveColumnInfoPageConfig(String columnJson) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemColumnInfoService.saveColumnInfoPageConfig(columnJson);
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
        }
        return jsonResultDto;
    }
}
